package org.csu.group4.jpetstore.controller;

import org.csu.group4.jpetstore.mybatis.entity.Category;
import org.csu.group4.jpetstore.mybatis.entity.Item;
import org.csu.group4.jpetstore.mybatis.entity.Product;
import org.csu.group4.jpetstore.service.CategoryService;
import org.csu.group4.jpetstore.service.ItemService;
import org.csu.group4.jpetstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/catalog")
public class ItemDisplayController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    ProductService productService;

    @Autowired
    ItemService itemService;

    @GetMapping(value = "/main")
    public String getMainPage(){
        return "catalog/Main";
    }

    @GetMapping(value = "/product/{categoryId}")
    public ModelAndView getProducts(@PathVariable String categoryId){
        ModelAndView modelAndView = new ModelAndView("catalog/Category");
        Category category =  categoryService.getById(categoryId.toUpperCase());
        List<Product> products = productService.getAllProductByCategory(category);
        modelAndView.addObject("products",products);
        return modelAndView;
    }
    @GetMapping(value = "/productId/{productId}")
    public ModelAndView getProductsById(@PathVariable String productId){
        Product product=productService.getByProductId(productId);
        return getProducts(product.getCategory().getCatId());
    }
    @GetMapping(value = "/item/{productId}")
    public ModelAndView getItems(@PathVariable String productId){
        ModelAndView modelAndView =new ModelAndView("catalog/Product");
        List<Item> items = itemService.getItems(productId);
        modelAndView.addObject("items",items);
        return modelAndView;
    }

    @GetMapping(value = "/itemId/{itemid}")
    public ModelAndView getItem(@PathVariable String itemid){
        ModelAndView modelAndView =new ModelAndView("catalog/Item");
        Item item = itemService.getItem(itemid);
        System.out.println(item);

        Product product = productService.getByProductId(item.getProductId());
        System.out.println(product);
        modelAndView.addObject("item",item);
        modelAndView.addObject("product",product);
        return modelAndView;
    }
    @PostMapping(value = "/search")
    public ModelAndView search(@RequestBody String keyword){
        return new ModelAndView("catalog/Product");
    }
}
